package november;

import java.io.IOException;
import java.util.Arrays;

/**
 * @author huangxin
 * @date 2019/6/19-14:13
 * 稀疏数组
 */
public class SparseArray {
    public static void main(String[] args) throws IOException {
        test2();
    }

    private static void test2() {
        int[][] arr = new int[6][10];
        arr[1][3] = 1;
        arr[2][3] = 5;

        System.out.println("原始数组");
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0) {
                    sum++;
                }
                System.out.printf("%d\t", arr[i][j]);
            }
            System.out.println();
        }

        //比有效数据的个数多1行,用于存储行列和个数
        int[][] sparseArr = new int[sum + 1][3];
        sparseArr[0][0] = arr.length; //行
        sparseArr[0][1] = arr[0].length; //列
        sparseArr[0][2] = sum; //列

        //下标
        int index = 1;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
                if (arr[i][j] != 0) {
                    //存储数据
                    sparseArr[i][0] = i;
                    sparseArr[i][1] = j;
                    sparseArr[i][2] = arr[i][j];
                    index++;
                }
            }
        }

        for (int i = 0; i < sparseArr.length; i++) {
            System.out.println(Arrays.toString(sparseArr[i]));
        }

        //恢复数组
        int[][] newArray = new int[sparseArr[0][0]][sparseArr[0][1]];
        for (int i = 1; i < sparseArr.length; i++) {
            for (int j = 0; j < sparseArr[i].length; j++) {
                int row = sparseArr[i][0];
                int column = sparseArr[i][1];
                int value = sparseArr[i][2];
                newArray[row][column] = value;
            }
        }

        for (int i = 0; i < newArray.length; i++) {
            System.out.println(Arrays.toString(newArray[i]));
        }
    }
}
